﻿using G_IS.Comm;
using G_IS.Extensions;
using Plusii.iiWeb;
using R.DMS.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace R.DMS.UI.Web
{
    public partial class UploadFiles : iiDialog
    {
        CommonBusiness service = new CommonBusiness();

        #region 属性

        /// <summary>
        /// 关联外键
        /// </summary>
        private int RelatedId
        {
            get
            {
                object tempObject = ViewState["RelatedId"];
                return (tempObject != null) ? (int)tempObject : 0;
            }
            set
            {
                ViewState["RelatedId"] = value;
            }
        }

        /// <summary>
        /// 文件类型
        /// </summary>
        private EnumUploadFileType UploadFileType
        {
            get
            {
                object tempObject = ViewState["UploadFileType"];
                return (tempObject != null) ? (EnumUploadFileType)tempObject : EnumUploadFileType.Unknown;
            }
            set
            {
                ViewState["UploadFileType"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                #region 验证权限

                #endregion

                #region 获取参数

                int relatedId;
                if (int.TryParse(Request.QueryString["RelatedId"], out relatedId))
                {
                    this.RelatedId = relatedId;
                }
                EnumUploadFileType upfileType;
                if (Enum.TryParse<EnumUploadFileType>(Request.QueryString["UploadFileType"], true, out upfileType))
                {
                    this.UploadFileType = upfileType;
                }

                #endregion

                //初始化
                this.Initialize();
            }

            #region 页面标题

            #endregion

            #region 页面要素

            #endregion
        }

        #region 初始化

        private void Initialize()
        {
            #region 页面内容

            //客户只能查看自己的内容
            if (LocalGlobal.CurrentUserType == "out")
            {
                //隐藏编辑功能
                UploadButton.Enabled = false;
                DeleteButton.Visible = false;
                List.Columns[0].Visible = false;
            }

            #endregion

            this.BindList();
        }

        #endregion

        #region 绑定数据

        private void BindList()
        {
            var list = service.GetFileList(string.Empty, RelatedId.ToString(), UploadFileType.GetHashCode().ToString())
                         .OrderByDescending(a => a.F_CreateTime)
                         .ToList();
            list.ForEach(f =>
            {
                string format = LocalGlobal.LinkFormat;
                f.F_Link = string.Format(format, f.F_FilePath, f.F_CreatorUserId, f.F_CreateTime.ToString(LocalGlobal.DateFormat), f.F_FileName.Trim());
            });

            List.DataSource = list;
            List.DataBind();
        }

        protected void List_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            switch (e.Row.RowType)
            {
                //数据行
                case DataControlRowType.DataRow:
                    #region 数据绑定

                    #endregion
                    break;

                case DataControlRowType.EmptyDataRow:
                case DataControlRowType.Header:
                case DataControlRowType.Separator:
                case DataControlRowType.Pager:
                case DataControlRowType.Footer:
                default:
                    break;
            }
        }

        #endregion

        #region 操作

        protected void UploadButton_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string extension = Path.GetExtension(FileUpload1.FileName);
                if (LocalGlobal.AllowFileTypes.Any(t => t.ToLower() == extension.ToLower()))
                {
                    DateTime currentTime = DateTime.Now;
                    string fileName = Path.GetFileName(FileUpload1.FileName);
                    string newFileName = Guid.NewGuid().ToString();

                    #region 目录

                    string typeName = EnumHelper.GetDesByValue<EnumUploadFileType>(UploadFileType.GetHashCode());
                    string subPath = string.Empty;
                    switch (this.UploadFileType)
                    {
                        case EnumUploadFileType.Contract:
                            var contract = service.GetContract(RelatedId);
                            if (contract != null)
                                subPath = contract.C_CustomerName;
                            break;
                        case EnumUploadFileType.Project:
                            var project = service.GetProject(RelatedId);
                            if (project != null)
                                subPath = project.P_CustomerName;
                            break;
                        case EnumUploadFileType.Patent:
                            var patent = service.GetPatent(RelatedId);
                            if (patent != null)
                                subPath = patent.Pa_CustomerName;
                            break;
                        case EnumUploadFileType.Policy:
                            var policy = service.GetPolicy(RelatedId);
                            if (policy != null)
                                subPath = policy.Po_TypeName;
                            break;
                    }

                    string uploadPhysicalPath = string.Format("{0}\\{1}\\{2}", LocalGlobal.UploadPhysicalPath, typeName, currentTime.ToString("yyyy")) + (subPath.IsEmpty() ? string.Empty : "\\" + subPath);
                    string uploadVirtualPath = string.Format("{0}/{1}/{2}", LocalGlobal.UploadVirtualPath, typeName, currentTime.ToString("yyyy")) + (subPath.IsEmpty() ? string.Empty : "/" + subPath);
                    if (!Directory.Exists(uploadPhysicalPath))
                    {
                        Directory.CreateDirectory(uploadPhysicalPath);
                    }

                    #endregion

                    #region 地址

                    string fullPhysicalPath = string.Format("{0}\\{1}{2}",
                        uploadPhysicalPath,
                        newFileName,
                        extension);
                    string fullVirtualPath = string.Format("{0}/{1}{2}",
                        uploadVirtualPath,
                        newFileName,
                        extension);

                    #endregion

                    try
                    {
                        FileUpload1.SaveAs(fullPhysicalPath);
                    }
                    catch (Exception error)
                    {
                        this.ShowErrorMessage("保存上传文档失败! " + error.Message);
                        return;
                    }

                    #region 处理数据

                    UploadFilesEntity upfile = new UploadFilesEntity();
                    upfile.F_RelatedId = RelatedId;
                    upfile.F_FileType = (byte)this.UploadFileType.GetHashCode();
                    upfile.F_FileName = fileName;
                    upfile.F_FilePath = fullVirtualPath;
                    upfile.F_FileExt = extension;
                    upfile.F_DeleteFlag = false;
                    upfile.F_CreateTime = currentTime;
                    upfile.F_CreatorUserId = iiGlobal.CurrentUserID;
                    upfile.F_CreatorUserName = iiGlobal.CurrentUser;

                    try
                    {
                        service.CreateFile(upfile);
                    }
                    catch (Exception error)
                    {
                        this.ShowErrorMessage("创建文档失败! " + error.Message);
                        return;
                    }

                    #endregion

                    this.BindList();
                }
                else
                {
                    this.ShowWarningMessage("此文档类型不允许上传!");
                    return;
                }
            }
            else
            {
                this.ShowWarningMessage("无文档上传!");
                return;
            }
        }

        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            bool hasDeletedItems = false;
            try
            {
                foreach (GridViewRow row in List.Rows)
                {
                    HtmlInputCheckBox rowCheckControl = (HtmlInputCheckBox)row.FindControl("RowCheck");
                    if (rowCheckControl.Checked)
                    {
                        var id = (int)List.DataKeys[row.RowIndex]["F_Id"];
                        var upfile = service.GetFile(id);
                        if (upfile != null)
                        {
                            #region 处理文件

                            try
                            {
                                File.Delete(Request.MapPath(upfile.F_FilePath));
                            }
                            catch { }

                            #endregion

                            service.DeleteFile(id);
                            hasDeletedItems = true;
                        }
                    }
                }
            }
            catch (Exception error)
            {
                this.ShowErrorMessage(this.GetGlobalResourceString("DeleteErrorMessage") + error.Message);
                return;
            }

            if (hasDeletedItems)
            {
                this.BindList();
            }
            else
            {
                this.ShowInfoMessage(this.GetGlobalResourceString("NotSelectMessage"));
                return;
            }
        }


        #endregion
    }
}